<template>
  <div class="container">
    <div class="title">
      <div class="icon"></div>
      <div class="text">{{ stationName }}</div>
    </div>
    <van-field
      v-model="amt"
      placeholder="消费金额"
      input-align="right"
      extra-event-params
      @focus="prevent"
      label="￥"
    />
    <van-number-keyboard
      :show="isShow"
      v-model="amt"
      theme="custom"
      extra-key="."
      close-button-text="确认支付"
      @blur="isShow = false"
      @close="checkPassword"
    />
    <van-overlay :show="true">
      <div class="wrapper" @click.stop>
        <div class="block">
          <van-loading size="48px">加载中...</van-loading>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script>
import Vue from "vue";
import { getAuthenSK } from "@/utils/getAuthenSK";
import querystring from "querystring";
import { mapMutations } from "vuex";
import { NumberKeyboard, Field, Loading, Overlay } from "vant";
Vue.use(NumberKeyboard);
Vue.use(Field);
Vue.use(Loading);
Vue.use(Overlay);

export default Vue.extend({
  head() {
    return {
      title: "付款"
    };
  },
  data() {
    return {
      redirect: "",
      tip: "认证中,请稍后...",
      amt: null,
      isShow: false,
      // enterpriseId: this.$store.state.authen.enterpriseId,
      stationName: this.$store.state.getSK.stationId,
      stationId: this.$store.state.getSK.stationName
    };
  },
  async created() {
    try {
      let type = 0;
      // 0 获取openid 常规流程（新用户，或者老用户清除了缓存之后）
      // 1 用户第一次，网站直接跳转 获取phone 正常流程
      // 2 用户通过会员卡界面激活，有openId无activateTicket 可能没有outerStr 其他同1 特殊流程
      // 3 已经激活的用户，木有了缓存，二次进入 正常流程

      let state = this.$route.query.state; // 0
      let code = this.$route.query.code; // 0

      let outerStr = this.$route.query.outer_str; // 1

      let cardId = this.$route.query.card_id; // 1 2
      let openId = this.$route.query.openid; // 1 2 3
      let activateTicket = this.$route.query.activate_ticket; // 1 2
      let encryptCode = this.$route.query.encrypt_code; // 1 2

      let phone = this.$route.query.phone; // 3
      let unionId = this.$route.query.unionid; // 3
      let originUrl = this.$route.query.originurl; // 3

      let enterpriseId = "";
      let consumerId = ""; // 消费者id , 走闪付阶段需要传当前登陆者的userId

      let extStr = "";
      if (!!state) {
        extStr = state;
        type = 0;
      } else if (!!outerStr) {
        extStr = outerStr;
        type = 1;
      } else if (!!cardId && !activateTicket) {
        type = 2;
      } else if (!!phone) {
        type = 3;
        extStr = originUrl;
      }

      // 用户直接访问
      if (!state && !outerStr && !cardId && !phone) {
        this.tip = "此页不支持直接访问";
        return;
      }

      // 解析url
      const urlInfo = this.parseExtStr(extStr);

      console.log("remitAuthSF---解析路径：", urlInfo);
      console.log("remitAuthSF---state:", state);
      console.log("remitAuthSF---outerStr", outerStr);
      console.log("remitAuthSF---openId", openId);
      console.log("remitAuthSF---activateTicket", activateTicket);
      console.log("remitAuthSF---encryptCode", encryptCode);
      console.log("remitAuthSF---phone", phone);
      console.log("remitAuthSF---unionId", unionId);
      console.log("remitAuthSF---originUrl", originUrl);
      console.log("remitAuthSF---enterpriseId", enterpriseId);
      console.log("remitAuthSF---extStr", extStr);
      console.log("remitAuthSF---type", type);
      console.log("remitAuthSF---consumerId", consumerId);

      if (type == 2) {
        //根据会员卡id拉取油企id 重定位跳转地址
        const enterpriseIdPro = await this.queryEnterpriseIdByCardId(cardId);
        enterpriseId = enterpriseIdPro.enterpriseId;
        this.redirect = "/" + enterpriseId + "/my/";
      } else {
        // 网址里面包含油企id，跳转网址在urlInfo里
        enterpriseId = urlInfo.enterpriseId;
        // 充值界面特殊处理
        if (urlInfo.firstUrl == "/charge/") {
          enterpriseId = urlInfo.searchObj.enterpriseId;
        } else if (urlInfo.firstUrl == "/plus/") {
          enterpriseId = urlInfo.searchObj.enterpriseId;
        }

        this.redirect = urlInfo.fullUrl;
      }
      // 没有油企id，强退
      if (!enterpriseId) {
        this.tip = "请访问站点网站";
        return;
      }

      if (type == 0) {
        // openid 认证 回来 -> 开始手机认证
        const openIdRes = await this.queryOpenIdByEnterpriseId(enterpriseId);
        const openId = openIdRes.openId;
        console.log("闪付授权中间页--存了openId" + openId);
        this.$store.commit("authen/setEnterpriseId", enterpriseId);
        this.$store.commit("authen/setOpenId", openId);

        console.log("再走一遍授权--有openId了", extStr);
        getAuthenSK(extStr, "remit");
        return;
      } else if (type == 1 || type == 2) {
        // type == 1  正常流程
        const phoneRes = await this.getPhoneByAuthenInfo(enterpriseId); // 原来的代码
        phone = phoneRes.phone;
        unionId = phoneRes.unionId;
        consumerId = phoneRes.consumerId;

        this.$store.commit("authen/setEnterpriseId", enterpriseId);
        this.$store.commit("authen/setOpenId", openId);
        this.$store.commit("authen/setPhone", phone);
        this.$store.commit("authen/setUnionId", unionId);
        this.$store.commit("authen/setConsumerId", consumerId);

        this.handleGotoPage();
      } else if (type == 3) {
        console.log("103---remitAuth.vue 的type", type);
        this.$store.commit("authen/setEnterpriseId", enterpriseId);
        this.$store.commit("authen/setOpenId", openId);
        this.$store.commit("authen/setPhone", phone);
        this.$store.commit("authen/setUnionId", unionId);

        this.handleGotoPage();
      }
    } catch (err) {
      console.log(err);
      const message = !!err.message ? err.message : err;
      alert(message);
    }
  },
  methods: {
    // 确认支付
    checkPassword() {
      this.amt = this.amt.toString().replace(/\.$/g, "");
      if (this.amt <= 0) return new Error("请输入金额");
      this.pay();
      this.isShow = false;
    },
    // 阻止手机输入框
    prevent() {
      document.activeElement.blur();
      this.isShow = true;
    },
    // test() {
    //   window.location.href =
    //     "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxab62cad69f646815&redirect_uri=https%3A%2F%2Fyh.xailife.com%2Fcash-register%2Fpages%2Fcash%2Findex%3Ffmno%3D301015200001138%26clientSerialNo%3D111111%26platform%3D2&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    // },
    parseExtStr(extStr) {
      let searchObj;
      let searchStr;
      let enterpriseId;

      const [url, str] = extStr.split(".");
      if (str !== undefined) {
        searchStr = str.replace(/-/g, "&").replace(/_/g, "=");
        searchObj = querystring.parse(searchStr);
      } else {
        searchStr = "";
        searchObj = {};
      }

      let enterpriseIdArr = url.replace(/\//, "").match(/^\d{1,}/);
      if (enterpriseIdArr == null) {
        enterpriseId = "";
      } else {
        enterpriseId = enterpriseIdArr[0];
      }

      return {
        fullUrl: url + (searchStr != "" ? "?" : "") + searchStr,
        firstUrl: url,
        searchObj,
        enterpriseId
      };
    },
    async getUserInfo() {
      console.log("手机号getUserInfo" + this.phone);
      try {
        const infoData = await this.$axios.$get("/getOrCreateUserInfo", {
          params: {
            enterpriseId: enterpriseId,
            openId: $nuxt.$store.getters["authen/openId"],
            nickName: ""
          }
        });

        if (infoData.retCode !== 0) {
          throw new Error(infoData.message);
        }
        this.setUserInfo(infoData.data);
        this.$store.commit("authen/setConsumerId", infoData.data.consumerId); // 保存消费者id
        console.log(infoData.data);
      } catch (error) {
        alert(error);
      }
    },
    async handleGotoPage() {
      await this.getUserInfo();
      console.log("1005--页面跳转---remitAuth", this.redirect);
      this.$router.replace({
        path: this.redirect
      });
    },
    // 获取openId
    async queryOpenIdByEnterpriseId(enterpriseId) {
      const code = this.$route.query.code;
      const gzhAuthenRes = await this.$axios.$get("/getGzhAuthorizeInfo", {
        params: {
          code,
          enterpriseId: enterpriseId
        }
      });
      if (gzhAuthenRes.retCode !== 0) {
        return Promise.reject("拉取openId失败");
      }
      const openId = gzhAuthenRes.data.openid;
      console.log("拉取的openId为", openId);
      return Promise.resolve({
        enterpriseId,
        openId
      });
    },
    async getPhoneByAuthenInfo(enterpriseId) {
      // 获取分享者id
      let shareUserId = Number(localStorage.getItem("shareUserId"));
      const encryptCode = this.$route.query.encrypt_code;
      const openId = this.$route.query.openid;
      const activateTicket = this.$route.query.activate_ticket;

      if (
        !!enterpriseId &&
        !!encryptCode &&
        !!openId &&
        !!activateTicket &&
        false
      ) {
        const gzhAuthenRes = await this.$axios.$post("/selectCardMobilePhone", {
          enterpriseId: enterpriseId,
          openId: openId,
          activateTicket: activateTicket,
          encryptCode: encryptCode
        });
        if (gzhAuthenRes.retCode !== 0) {
          return Promise.reject("拉取手机号失败");
        }
        const phone = gzhAuthenRes.data.phone;
        const unionId = gzhAuthenRes.data.unionid;
        // commit("setOpenId", openId)
        // commit ("setPhone", phone)
        // commit ("setUnionId", unionId)
        return Promise.resolve({
          phone,
          unionId
        });
      } else if (!!enterpriseId && !!encryptCode && !!openId) {
        // 根据是否存在分享者shareUserId，给后端传对应的分享者id，让后端给shareUserId对应的用户增加拉取新人的次数
        let gzhAuthenRes = await this.$axios.$post("/selectWxMemberCardInfo", {
          enterpriseId: enterpriseId,
          openId: openId,
          encryptCode: encryptCode
        });

        if (gzhAuthenRes.retCode !== 0) {
          return Promise.reject(gzhAuthenRes.message);
        }
        const phone = gzhAuthenRes.data.mobilePhone;
        const unionId = gzhAuthenRes.data.unionid;

        return Promise.resolve({
          phone,
          unionId
        });
      } else {
        throw new Error("authen参数不全");
      }
    },
    // 根据cardId拿enterpriseId
    async queryEnterpriseIdByCardId(cardId) {
      const enterpriseIdPro = await this.$axios.$get(
        "/selectEnterpriseIdByCardId",
        {
          params: {
            cardId
          }
        }
      );
      if (enterpriseIdPro.retCode != 0) {
        return Promise.reject("拉取EnterpriseId失败");
      }
      return Promise.resolve({
        cardId: cardId,
        enterpriseId: enterpriseIdPro.data
      });
    },

    // 根据enterpriseId 拿appId
    async queryAppIdByEnterpriseId(enterpriseId) {
      const appIdRes = await this.$axios.$get("/getStationGzhAppId", {
        params: {
          enterpriseId
        }
      });
      if (appIdRes.retCode != 0) {
        return Promise.reject("获取appid失败");
      }
      // commit("setAppId", appIdRes.data.appId)
      return Promise.resolve({
        enterpriseId,
        appId: appIdRes.data.appId
      });
    },
    ...mapMutations({
      setEnterpriseId: "authen/setEnterpriseId",
      setAppId: "authen/setAppId",
      setTempEnterpriseId: "setTempEnterpriseId",
      setUserInfo: "authen/setUserInfo"
    })
    // ...mapActions({
    //   getAppId: "authen/getAppId",
    // }),
  }
});
</script>
<style lang="scss" scoped>
.container {
  box-sizing: border-box;
  min-height: 100vh;
  background-color: #f5f6f7;
  padding: 0.2rem;
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    z-index: 11;
  }

  .block {
    width: 120px;
    height: 120px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .title {
    display: flex;
    align-items: center;
    .icon {
      background: url("../static/fuel/jiayouzhan.png") no-repeat;
      width: 1.5rem;
      height: 1.5rem;
      background-size: 100% 100%;
      margin: 0.2rem;
      border-radius: 50%;
    }
    .text {
      font-size: 20px;
      //   height: 1.5rem;
      //   line-height: 1.5rem;
      word-break: break-all;
      flex: 1;
    }
  }
  ::-webkit-input-placeholder {
    text-align-last: left;
  }
  .label-focus {
    font-size: 12px;
    transform: translate3d(0, -12px, 0);
  }

  .label-blur {
    font-size: 16px;
    transform: translate3d(0, 0, 0);
  }
}

.van-cell {
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  box-sizing: border-box;
  width: 100%;
  padding: 20px 16px;
  overflow: hidden;
  color: #323233;
  font-size: 20px;
  line-height: 30px;
  background-color: #fff;
}
</style>
